﻿using System;
using System.Windows;
using System.Collections.Generic;
using System.Reflection;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Controls;
using Baosight.ZNH.ZMCA.UI.Utils;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;
using Baosight.ZNH.ZMCA.UI.Model;


namespace Baosight.ZNH.ZMCA.UI
{
    /// <summary>
    /// ZMCA13对数据的处理与ZMCA12一样
    /// </summary>
    public partial class ZMCA13 : EFView
    {
        ZMCA13Controler controler = new ZMCA13Controler();
        public ZMCA13()
        {
            InitializeComponent();
            FillGaugeData();
            FillChartData(this.chart);
            FillListViewData();

        }

        private void FillListViewData()
        {
            controler.GetListViewData(lstView);
        }

        private void FillGaugeData()
        {
            controler.GetGaugeData(gauge);
        }


        public void FillChartData(RadChart chart)
        {
            controler.GetChartData(chart);
        }
    }

    public class ZMCA13Controler
    {
        DoubleCircleGauge gauge;
        RadChart chart;
        RadTreeListView lstView;
        public ZMCA13Controler()
        {
            
        }

        #region 获取刷新Gauge图

        public void GetGaugeData(DoubleCircleGauge gauge)
        {
            this.gauge = gauge;
            gauge.gaugeTitle.Text = "井下三违";
            gauge.leftGaugeDescription.Text = "当月(个)";
            gauge.rightGaugeDescription.Text = "昨日(个)";

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByIndex");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getGaugeDataCompleted);
        }

        private void getGaugeDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }
            EIInfo eiInfo = e.EIInfo;
            EIBlock result = eiInfo.GetBlock("result");
            if (result != null && result.Rows.Count > 0)
            {
                foreach (var item in result.Rows)
                {
                    //年度数据的fdRiskDate长度为4，昨天数据的fdRiskDate长度为10（2011vs2011-05-05）
                    if (item["fdDate"].ToString().Length == 7)
                    {
                        gauge.leftNeedle.Value = Common.GetIntValue(item["fdKeyId"]);
                    }
                    else
                    {
                        gauge.rightNeedle.Value = Common.GetIntValue(item["fdKeyId"]);
                    }
                }
            }

            gauge.leftControler.IsReverse = true;
            gauge.rightControler.IsReverse = true;
        }

        #endregion

        #region 获取刷新RadChart图

        public void GetChartData(RadChart chart)
        {
            this.chart = chart;

            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByChart");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getChartDataCompleted);
        }

        private void getChartDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }
            EIInfo eiInfo = e.EIInfo;
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByYearClassify = eiInfo.GetBlock("queryByYearClassify");
            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));

            chart.DefaultView.ChartTitle.Content = currentYear + "井下三违类别趋势分析";
            chart.DefaultSeriesDefinition.ShowItemToolTips = true;
            chart.DefaultSeriesDefinition.LegendDisplayMode = LegendDisplayMode.DataPointLabel;
            chart.DefaultView.ChartLegend.Header = string.Empty;

            this.chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            this.chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            this.chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            SeriesMapping sm1 = new SeriesMapping();
            BarSeriesDefinition totalBar = new BarSeriesDefinition();
            sm1.SeriesDefinition = totalBar;
            sm1.LegendLabel = "Bar Series";
            sm1.CollectionIndex = 0;
            sm1.LegendLabel = "三违总数";
            sm1.SeriesDefinition.ShowItemLabels = false;
            sm1.SeriesDefinition.ShowItemToolTips = true;
            sm1.SeriesDefinition.ShowZeroValuesLabels = true;
            sm1.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
            sm1.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
            sm1.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
            sm1.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;
            chart.SeriesMappings.Add(sm1);

            List<List<ChartData>> itemsSource = new List<List<ChartData>>();
            List<ChartData> totalList = new List<ChartData>();
            for (int i = 1; i <= currentMonth; i++)
			{
                totalList.Add(new ChartData(i + "月", 0));
			}
            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }
                AddChartDate(item, date, totalList);
            }
            itemsSource.Add(totalList);

            GetClassData(queryByYearClassify, currentMonth, itemsSource);

            chart.ItemsSource = itemsSource;
        }

        private void GetClassData(EIBlock queryByYearClassify, int currentMonth, List<List<ChartData>> itemsSource)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (var item in queryByYearClassify.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                if (!dic.ContainsKey(item["fdClassify"].ToString()))
                {
                    List<ChartData> levelList = new List<ChartData>();
                    for (int i = 1; i <= currentMonth; i++)
                    {
                        levelList.Add(new ChartData(i + "月", 0));
                    }
                    itemsSource.Add(levelList);
                    dic.Add(item["fdClassify"].ToString(), itemsSource.Count - 1);

                    SeriesMapping sm2 = new SeriesMapping();
                    SplineSeriesDefinition d2 = new SplineSeriesDefinition();
                    sm2.SeriesDefinition = d2;
                    sm2.LegendLabel = item["fdClassify"].ToString();
                    sm2.CollectionIndex = itemsSource.Count - 1;
                    sm2.SeriesDefinition.ShowItemLabels = false;
                    sm2.SeriesDefinition.ShowItemToolTips = true;
                    sm2.SeriesDefinition.ShowZeroValuesLabels = true;
                    sm2.ItemMappings.Add(new ItemMapping("Date", DataPointMember.XCategory));
                    sm2.ItemMappings.Add(new ItemMapping("DataValue", DataPointMember.YValue));
                    sm2.SeriesDefinition.InteractivitySettings.HoverScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionScope = InteractivityScope.Series;
                    sm2.SeriesDefinition.InteractivitySettings.SelectionMode = ChartSelectionMode.Multiple;

                    chart.SeriesMappings.Add(sm2);
                }
                List<ChartData> tList = itemsSource[dic[item["fdClassify"].ToString()]];

                AddChartDate(item, date, tList);
            }
        }

        private static void AddChartDate(EIRow item, string date, List<ChartData> tList)
        {
            if (date[5] == '0')
            {
                date = date.Substring(6);
            }
            else
            {
                date = date.Substring(5);
            }
            if (Common.GetIntValue(date) - 1 < tList.Count)
            {
                tList[Common.GetIntValue(date) - 1].DataValue = Common.GetDecimalValue(item["fdKeyId"].ToString());
            }
        }

        #endregion

        #region 获取刷新RadListView数据表数据

        public void GetListViewData(RadTreeListView lstView)
        {
            this.lstView = lstView;
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCA13");
            eiInfo.Set("method", "queryByListView");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, getListViewDataCompleted);
        }

        private void getListViewDataCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                Common.Alert(Common.MsgLoadDataError);
                return;
            }

            EIInfo eiInfo = e.EIInfo;
            EIBlock queryByYear = eiInfo.GetBlock("queryByYear");
            EIBlock queryByDepartment = eiInfo.GetBlock("queryByDepartment");
            EIBlock queryByListC = eiInfo.GetBlock("queryByListC");

            int currentMonth = Common.GetIntValue(eiInfo.Get("month"));
            int currentYear = Common.GetIntValue(eiInfo.Get("year"));


            for (int i = 12 - currentMonth + 2; i > 2; i--)
            {
                var cl = lstView.Columns[i];
                cl.IsVisible = false;
            }

            List<ZMCA12DetailItem> itemsSource = new List<ZMCA12DetailItem>();

            ZMCA12DetailItem yearItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearDepartmentItem = new ZMCA12DetailItem();
            ZMCA12DetailItem yearClassifyItem = new ZMCA12DetailItem();

            itemsSource.Add(yearItem);
            Type itemType = yearItem.GetType();
            yearItem.Name = "全矿";
            yearClassifyItem.Name = "所有类别";
            yearItem.Items.Add(yearClassifyItem);
            yearDepartmentItem.Name = "所有单位";
            yearItem.Items.Add(yearDepartmentItem);

            foreach (var item in queryByYear.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Length == 10)
                {
                    yearItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    yearClassifyItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    //yearDepartmentItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(yearItem, Common.GetIntValue(item["fdKeyId"]), null);
                pi.SetValue(yearClassifyItem, Common.GetIntValue(item["fdKeyId"]), null);
                //pi.SetValue(yearDepartmentItem, Common.GetIntValue(item["fdKeyId"]), null);
            }

            AddChildItemByBlock(queryByListC, yearClassifyItem, itemType, "fdClassify");
            AddDepartmentChildItemByBlock(queryByDepartment, yearDepartmentItem, itemType);

            lstView.ItemsSource = itemsSource;
        }

        private static void AddChildItemByBlock(EIBlock block, ZMCA12DetailItem parentDetailItem, Type itemType, string columnName)
        {
            ZMCA12DetailItem detailItem = null;
            foreach (var item in block.Rows)
            {
                string date = item["fdDate"].ToString();
                if (date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemName = item[columnName].ToString();
                if (detailItem == null || detailItem.Name != itemName)
                {
                    detailItem = new ZMCA12DetailItem();
                    parentDetailItem.Items.Add(detailItem);
                    detailItem.Name = itemName;
                }

                if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
        }

        private void AddDepartmentChildItemByBlock(EIBlock block, ZMCA12DetailItem parentDetailItem, Type itemType)
        {
            Dictionary<string, ZMCA12DetailItem> dic = new Dictionary<string, ZMCA12DetailItem>();
            ZMCA12DetailItem detailItem = null;
            foreach (var item in block.Rows)
            {
                string date = Common.GetStringValue(item["fdDate"]);
                if (item["fdDate"]!=null && date.Trim() == string.Empty)
                {
                    continue;
                }

                string itemUniqueName = Common.GetStringValue(item["fdResponseDepartmentId"]);
                if (detailItem == null || detailItem.UniqueName != itemUniqueName)
                {
                    detailItem = new ZMCA12DetailItem();
                    dic.Add(itemUniqueName, detailItem);
                    if (Common.GetIntValue(item["fdDepartmentLevel"]) == 1)
                    {
                        parentDetailItem.Items.Add(detailItem);
                    }
                    else
                    {
                        if (dic.ContainsKey(item["fdParentDepartmentId"].ToString()))
                        {
                            dic[item["fdParentDepartmentId"].ToString()].Items.Add(detailItem);
                        }
                        else
                        {
                            parentDetailItem.Items.Add(detailItem);
                            //单位层级有问题，找不到父亲单位
                        }
                    }
                    detailItem.UniqueName = itemUniqueName;

                    detailItem.Name = item["fdDepartmentName"].ToString();
                }

                if(date == string.Empty)
                {
                    continue;
                }
                else if (date.Length == 10)
                {
                    detailItem.Yesterday = Common.GetIntValue(item["fdKeyId"]);
                    continue;
                }
                if (date[5] == '0')
                {
                    date = date.Substring(6);
                }
                else
                {
                    date = date.Substring(5);
                }

                PropertyInfo pi = itemType.GetProperty("M" + date);
                pi.SetValue(detailItem, Common.GetIntValue(item["fdKeyId"]), null);
            }
            ZMCA12DetailItem.SummarizedChildItemData(parentDetailItem);
        }

        #endregion
    }
}